let config = require('./config.js');
let XCX = {
  //接口请求
  requestData: function (method, url, params, isLoading) {
    return new Promise((resolve, reject) => {
      //判断是否有网络
      wx.getNetworkType({
        success: function (net) {
          if (net.networkType != 'none') { //有网，进行数据请求
            if (isLoading) {
              wx.showLoading();
            }
            let requestUrl = config.apiHost02 + url;
            // if(url=="InviteHistory/SaveHistory" || url=="Live/GetRoomData" || url=="Live/GetRoomItem" || url=="Live/SavePlayTimeV2" || url=="InviteHistory/GetInvite"){
            //   requestUrl = config.apiHost01 + url;
            // }else if(url.indexOf('WeChat/')!=-1 || url.indexOf('Member/')!=-1 || url.indexOf('MemberAddress/')!=-1 || url.indexOf('LiveRoom/')!=-1 || url.indexOf('Live/S')!=-1){
            //   requestUrl = config.apiHost02 + url;
            // }
            wx.request({
              url: requestUrl,
              method: method,
              data: params ? params : {},
              header: {
                'Content-Type': "application/json", //"application/x-www-form-urlencoded";//表单格式,
                "token": config.TOKEN(),  
                "openid": config.OPENID()
              },
              success: function (res) {
                if (res.data.Tag == 97) { //token 过期失效
                  XCX.showToast("登录已过期");
                  XCX.refreshToken();//更新token
                } else {
                  resolve(res.data);
                }
              },
              fail: function (err) {
                //XCX.showToast("服务器繁忙，请稍后重试");
                if (isLoading) {
                  wx.hideLoading();
                }
                setTimeout(function(){
                  XCX.RetryRequst(method, requestUrl, params ? params : {}, 3, function () {
                    resolve(res.data);
                  }, function () { reject(err); });
                },1200);
              },
              complete: (e) => {
                if (isLoading) {
                  wx.hideLoading();
                }
              }
            });
          } else {
            XCX.showToast('请切换网络');
          }
        },
        fail: function (e) {
          XCX.showToast('请切换网络');
        }
      })

    })
  },
  /** 重试请求 3次 */
  RetryRequst(method, url, data, retryCount, funOK, funError) {
    wx.request({
      method: method,
      url: url,
      data: data,
      header: {
        'Content-Type': "application/json", //"application/x-www-form-urlencoded";//表单格式,
        "token": config.TOKEN(), // "da814aa408a9e55d7565d9c33ced3cf2" // 
        "openid": config.OPENID()
      },
      success: function (res) {
        // 请求成功的处理逻辑
        console.log('请求成功', res);
        funOK(res);
      },
      fail: function (error) {
        // 请求失败的处理逻辑
        console.log('请求失败', error);
        // 判断是否还有重试次数
        if (retryCount > 0) {
          console.log('进行重试，剩余重试次数：', retryCount);
          // 重新发送请求，减少重试次数
          XCX.RetryRequst(method, url, data, retryCount - 1, funOK, funError);
        } else {
          XCX.showToast("服务器繁忙，请稍后重试");
          funError();
          console.log('重试次数已用完，请求失败');
        }
      }
    });
  },

  /** 刷新token */
  refreshToken() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.apiHost + 'WeChat/RefreshToken',
        method: "POST",
        data: {
          appletId: config.OPENID()
        },
        header: {
          'Content-Type': "application/json", //"application/x-www-form-urlencoded";//表单格式,
          "token": config.TOKEN(),
          "openid": config.OPENID()
        },
        success: function (res) {
          // resolve(res.data);
          if (res.data.Tag == 10) {
            config.setLoginInfo("TOKEN", res.data.Data);
            wx.switchTab({
              url: '/pages/homepage/index',
            })
          }
        },
        fail: function (e) {
          reject(e);
        }
      })
    })
  },

  //保存错误日志接口请求
  saveLogErr: function (method, url, params) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.hostUrl + url,
        method: method,
        data: params ? params : {},
        header: {
          'Content-Type': "application/json", //"application/x-www-form-urlencoded";//表单格式,
          "token": config.TOKEN()
        },
        success: function (res) {
          resolve(res.data);
        },
        fail: function (e) {
          reject(e);
        }
      })
    })
  },

  //页面跳转
  href: function (url, e) {
    let pages = getCurrentPages();
    if (e || pages.length == 10) { //当前页面层级达到10层
      wx.redirectTo({
        url: url
      })
    } else {
      wx.navigateTo({
        url: url
      })
    }
  },
  //信息提示
  showToast: function (title) {
    //延迟为了解决在wx.hideLoading()之后，真机一闪而过问
    setTimeout(() => {
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }, 300);
  },
  showModal: function (title, content, isCancel, callBack) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: isCancel,
      success: (result) => {
        callBack(result);
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  }

}

module.exports = {
  http: XCX
}